import { message } from "antd";
import React, { useCallback } from "react";
import { useState, useEffect } from "react";
import { MAX_FILE_SIZE } from "./constant";
export default function useDrag(uploadContainerRef) {
	const [selectedFile, setSelectedFile] = useState(null); //保存用户选中的文件
	//存放文件预览信息
	//url：预览地址  type：文件类型
	const [filePreview, setFilePreview] = useState({ url: null, type: null });
	const handleDrag = useCallback((event) => {
		event.preventDefault(); //阻止默认行为
		event.stopPropagation(); //阻止事件传播
	}, []);
	const checkFile = (files) => {
		const file = files[0];
		if (!file) {
			message.error("没有选择任何文件");
			return;
		}
		//文件大小不能超过2g
		if (file.size > MAX_FILE_SIZE) {
			message.error("文件大小不能超过2GB");
			return;
		}
		//判断文件类型
		if (!(file.type.startsWith("image/") || file.type.startsWith("video/"))) {
			message.error("文件文件类型必须是图片或视频");
			return;
		}
		setSelectedFile(file);
	};
	const handleDrop = useCallback((event) => {
		event.preventDefault(); //阻止默认行为
		event.stopPropagation(); //阻止事件传播
		checkFile(event.dataTransfer.files);
		// const files = event.dataTransfer.files[0]; //拿到文件名
		// console.log(files);
	}, []);
	useEffect(() => {
		if (!selectedFile) return;
		const url = URL.createObjectURL(selectedFile);
		setFilePreview({ url, type: selectedFile.type });
		//ueEffect返回一个销毁函数
		return () => {
			URL.revokeObjectURL(url); //revokeObjectURL可以撤销此URL占用的资源
		};
	}, [selectedFile]);
	useEffect(() => {
		const uploadContainer = uploadContainerRef.current;
		uploadContainer.addEventListener("dragenter", handleDrag);
		uploadContainer.addEventListener("dragover", handleDrag);
		uploadContainer.addEventListener("drop", handleDrop);
		uploadContainer.addEventListener("dragleave", handleDrag);
		return () => {
			uploadContainer.removeEventListener("dragenter", handleDrag);
			uploadContainer.removeEventListener("dragover", handleDrag);
			uploadContainer.removeEventListener("drop", handleDrop);
			uploadContainer.removeEventListener("dragleave", handleDrag);
		};
	}, []);
	//实现点击上传
	useEffect(() => {
		const uploadContainer = uploadContainerRef.current;
		uploadContainer.addEventListener("click", () => {
			const fileInput = document.createElement("input");
			fileInput.type = "file";
			fileInput.style.display = "none";
			fileInput.addEventListener("change", (event) => {
				checkFile(event.target.files);
			});
			document.body.appendChild(fileInput);
			//手动触发文件选择
			fileInput.click();
		});
	}, []);
	const resetFileStatus = () => {
		setSelectedFile(null);
		setFilePreview({ url: null, type: null }); //重置filePreview状态为初始值
	};
	return { selectedFile, filePreview, resetFileStatus };
}
